const pool = require('./db');

async function testManualInsert() {
    console.log('🧪 手动测试插入数据...');
    
    const connection = await pool.getConnection();
    
    try {
        await connection.beginTransaction();
        
        const songName = '测试歌曲-' + Date.now();
        const artistName = '测试歌手-' + Date.now();
        const audioUrl = 'http://localhost:3000/test-audio-url';
        
        console.log('📝 准备插入数据:');
        console.log('  歌名:', songName);
        console.log('  歌手:', artistName);
        
        // 1. 先添加歌手
        console.log('\n1️⃣ 添加歌手到songers表...');
        const [artistResult] = await connection.execute(
            'INSERT INTO songers (name) VALUES (?)', 
            [artistName]
        );
        const artistId = artistResult.insertId;
        console.log('✅ 歌手添加成功，ID:', artistId);
        
        // 2. 再添加歌曲
        console.log('\n2️⃣ 添加歌曲到songs表...');
        const [songResult] = await connection.execute(
            'INSERT INTO songs (title, artist, song_url, artist_id) VALUES (?, ?, ?, ?)', 
            [songName, artistName, audioUrl, artistId]
        );
        const songId = songResult.insertId;
        console.log('✅ 歌曲添加成功，ID:', songId);
        
        await connection.commit();
        
        // 3. 验证插入结果
        console.log('\n3️⃣ 验证插入结果...');
        const [songs] = await connection.execute('SELECT * FROM songs WHERE id = ?', [songId]);
        const [singers] = await connection.execute('SELECT * FROM songers WHERE id = ?', [artistId]);
        
        console.log('歌曲记录:', songs[0]);
        console.log('歌手记录:', singers[0]);
        
        console.log('\n✅ 手动插入测试成功！');
        
    } catch (error) {
        await connection.rollback();
        console.error('❌ 插入失败:', error);
    } finally {
        connection.release();
    }
}

testManualInsert().then(() => {
    console.log('\n🏁 测试完成');
    process.exit(0);
}).catch(error => {
    console.error('测试失败:', error);
    process.exit(1);
});